import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:like_button/like_button.dart';
import 'package:projectone/bean/books_bean.dart';
import 'package:projectone/link_url.dart';
import 'dart:convert';
import 'event_bus.dart';
import 'network_get_data.dart';
import 'db_util.dart';

///书籍信息界面
class BookInfoPage extends StatefulWidget{
  final String bookUrl;
  final String bookName;

  BookInfoPage(this.bookUrl,this.bookName);

  @override
  _BookInfoState createState() {
    // TODO: implement createState
   return _BookInfoState(bookUrl,bookName);
  }

}
class _BookInfoState extends State<BookInfoPage>{
  final String bookUrl;
  final String bookName;
  bool _isLike=false;
  _BookInfoState(this.bookUrl,this.bookName);
  BookDetailBean bookDetailBean=
  new BookDetailBean(bookName:'加载中',bookId: '0',lastName: '加载中。。。',lastLink: 'lastLink',author: '加载中。。。',bookCover: 'http://www.xbiqige.com/public/image/nocover.jpg',bookIntro: '加载中。。。', bookChapter: new List());
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //检查书本又没有收藏
    DBUtil.dbUtil.haveBook(bookName).then((value) => _isLike=value);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      EasyLoading.show(status: 'loading...');
    });
    NetworkData().getBookDetail(bookUrl).then((bookDetail){
      setState(() {
        bookDetailBean=bookDetail;
        EasyLoading.dismiss();
      });
    });
  }
  Future<bool> onLikeButtonTapped(bool isLiked) async{
    /// send your request here
    // final bool success= await sendRequest();
    if(_isLike){
      //取消收藏
      DBUtil.dbUtil.deleteBook(bookDetailBean.bookName);
      eventBus.fire(BookListRefreshEvent(true,2));
    }else{
      //加入收藏
      String jsonData=json.encode(bookDetailBean);
      DBUtil.dbUtil.insertBook(bookDetailBean.bookName, bookUrl, bookDetailBean.bookCover, jsonData, bookDetailBean.bookChapter[0].chapterLink);
      eventBus.fire(BookListRefreshEvent(true,1));
    }

    /// if failed, you can do nothing
    // return success? !isLiked:isLiked;
    _isLike=!isLiked;
    return !isLiked;
  }
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text(bookName),
        centerTitle: true,
        actions: <Widget>[
          LikeButton(isLiked: _isLike,onTap: onLikeButtonTapped,)
        ],
      ),
      body: Column(
        children: <Widget>[
          Row(
            children: <Widget>[
              new Container(
                  padding: EdgeInsets.all(4),
                  child: new Image(
                      height: 170,
                      width: 137,
                      image: NetworkImage(bookDetailBean.bookCover))),
              new Expanded(child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  new Text('《'+bookDetailBean.bookName+'》'),
                  new Divider(color: Colors.grey,height: 1,),
                  new Text(bookDetailBean.author),
                  new Divider(color: Colors.grey,height: 1,),
                  new Text('最新章节:'+bookDetailBean.lastName)
                ],
              ))
            ],
          ),
          Text(bookDetailBean.bookIntro,maxLines: 5,overflow: TextOverflow.ellipsis,),
          new Divider(height: 20,),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              MaterialButton(textColor: Colors.white,color: Colors.blue,
               child: Text('开始阅读'),
               onPressed: (){
                 //从第一章阅读
                 Navigator.push(context, MaterialPageRoute(builder: (context){
                   return ReadBookPage(bookUrl,bookDetailBean, bookDetailBean.bookChapter[0].chapterLink);
                 }));
               },),
              Container(height:0,width: 30,),
              MaterialButton(textColor: Colors.white,color: Colors.green,
                child: Text('章节目录'),
                onPressed: (){
                  //进入章节目录
                  Navigator.push(context, MaterialPageRoute(builder: (context){
                    return BookChapterPage(bookDetailBean,bookUrl,bookDetailBean.bookName,bookDetailBean.bookChapter);
                  }));
                },)
          ],)
        ],
      )
    );
  }
}

///章节列表页面
class BookChapterPage extends StatelessWidget{
  final String bookName;
  final String bookUrl;
  final List<BookChapter> chapterList;
  final BookDetailBean bookDetailBean;
  BookChapterPage(this.bookDetailBean,this.bookUrl,this.bookName, this.chapterList);
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new Scaffold(
      appBar: AppBar(title: Text(bookName),centerTitle: true,),
      body: ListView.builder(
          itemCount: chapterList.length,
          itemBuilder: (BuildContext context,int i){
            BookChapter temp=chapterList[i];
        return Container(
          child: ListTile(
            title: Text(chapterList[i].chapterName),onTap: (){
            DBUtil.dbUtil.updateBook(bookDetailBean.bookName, temp.chapterLink);
            eventBus.fire(BookListRefreshEvent(true,3));
            //跳转到
            Navigator.push(context, MaterialPageRoute(builder: (context){
              return ReadBookPage(bookUrl,bookDetailBean,
                  temp.chapterLink);
            }));
          },
          ),
          color: i%2==0?Colors.white:Colors.grey,
        );
      }),
    );
  }
}

///阅读界面
class ReadBookPage extends StatefulWidget{
  final String bookUrl;
  final String chapterUrl;
  final BookDetailBean bookDetailBean;
  ReadBookPage(this.bookUrl,this.bookDetailBean, this.chapterUrl);

  @override
  _ReadBookState createState() {
    // TODO: implement createState
    return _ReadBookState(bookDetailBean,bookUrl,chapterUrl);
  }
}
class _ReadBookState extends State<ReadBookPage>{
  final BookDetailBean bookDetailBean;
  final String bookUrl;
  final String chapterUrl;
  _ReadBookState(this.bookDetailBean,this.bookUrl, this.chapterUrl);
  String content='';
  int _chapterId;
  String _readingChapter;
  ScrollController _scrollController=new ScrollController();
  bool _isLiked=false;
  @override
    void initState() {
      // TODO: implement initState
      super.initState();
      _readingChapter=chapterUrl;
      List<String> cha=chapterUrl.split('/');
      _chapterId=int.parse(cha[cha.length-2]);
      DBUtil.dbUtil.haveBook(bookDetailBean.bookName).then((value) => _isLiked=value);
      WidgetsBinding.instance.addPostFrameCallback((_) {
        EasyLoading.show(status: 'loading...');
      });
      NetworkData().getBookContent(chapterUrl).then((value) =>
      setState(() {
        content=value;
        EasyLoading.dismiss();
      }));
    }
    List<BookFavoriteBean> likeList=new List();
  _getLastChapter(){
    if(_chapterId==1) EasyLoading.showInfo('这里就是第一章了');
    else{
      _chapterId--;
      final lastUrl=urlApi.contentBaseUrl+'${bookDetailBean.bookId}/$_chapterId/';
      _readingChapter=lastUrl;
      EasyLoading.show(status :'loading...');
      NetworkData().getBookContent(lastUrl).then((value) =>
          setState(() {
            content=value;
            EasyLoading.dismiss();
            _scrollController.jumpTo(0);
            DBUtil.dbUtil.updateBook(bookDetailBean.bookName, _readingChapter);
            eventBus.fire(BookListRefreshEvent(true,3));
          }));
    }
  }
  _getNextChapter(){
    if(_chapterId==bookDetailBean.bookChapter.length) EasyLoading.showInfo('本书已经读完！');
    else{
      _chapterId++;
      final url=urlApi.contentBaseUrl+'${bookDetailBean.bookId}/$_chapterId/';
      _readingChapter=url;
      EasyLoading.show(status :'loading...');
      NetworkData().getBookContent(url).then((value) =>
          setState(() {
            content=value;
            EasyLoading.dismiss();
            _scrollController.jumpTo(0);
            DBUtil.dbUtil.updateBook(bookDetailBean.bookName, _readingChapter);
            eventBus.fire(BookListRefreshEvent(true,3));
          }));
    }
  }
  Future<bool> onLikeButtonTapped(bool isLiked) async{
    /// send your request here
    // final bool success= await sendRequest();
    if(_isLiked){
      //取消收藏
      DBUtil.dbUtil.deleteBook(bookDetailBean.bookName);
      eventBus.fire(BookListRefreshEvent(true,2));
    }else{
      //加入收藏
      String jsonData=json.encode(bookDetailBean);
      DBUtil.dbUtil.insertBook(bookDetailBean.bookName, bookUrl, bookDetailBean.bookCover, jsonData, _readingChapter);
      eventBus.fire(BookListRefreshEvent(true,1));
    }

    /// if failed, you can do nothing
    // return success? !isLiked:isLiked;
    _isLiked=!isLiked;
    return !isLiked;
  }
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(title: Text(bookDetailBean.bookChapter[_chapterId-1].chapterName),centerTitle: true,actions: <Widget>[
        LikeButton(isLiked:_isLiked,onTap: onLikeButtonTapped,)
      ],),
      body: SingleChildScrollView(
            controller: _scrollController,
              child: Column(
                children: <Widget>[
                  Text(content),
                  Divider(height: 55,)
                ],
              ),
      ),
      bottomSheet: Row(
        children: <Widget>[
          Expanded(
            child: MaterialButton(textColor: Colors.white,color: Colors.green,child: Text('<-上一章'),onPressed: (){
            _getLastChapter();
            },),
          ),
          Expanded(
          child: MaterialButton(textColor: Colors.white,color: Colors.blue,child: Text('下一章->'),onPressed: (){
              _getNextChapter();
          },),
          )
        ],
      ),
    );
  }

}